{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4f910d7f",
   "metadata": {},
   "outputs": [],
   "source": [
    "from onekey_algo.custom.Manager import onekey_show\n",
    "\n",
    "onekey_show('模型可解释性-SHAP')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "44a6c6e1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import shap\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import joblib\n",
    "import os\n",
    "\n",
    "model_path = r'C:\\Users\\onekey\\Desktop\\onekey_comp\\comp9-Solutions\\sol1. 传统组学-单中心-临床\\models/LightGBM_label.pkl'\n",
    "feature_path = r'C:\\Users\\onekey\\Desktop\\onekey_comp\\comp9-Solutions\\sol1. 传统组学-单中心-临床/final_features.csv'\n",
    "analysis_label = 1\n",
    "analysis_sample = 149 "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ab657a94",
   "metadata": {},
   "source": [
    "# 模型全部样本的SHAP分布"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5719c8c3",
   "metadata": {},
   "outputs": [],
   "source": [
    "from onekey_algo.custom.viz.shap_clf import get_explainer, get_shap_value\n",
    "\n",
    "os.makedirs('img', exist_ok=True)\n",
    "explainer, model, features, shap_values = get_explainer(model_path, feature_path)\n",
    "shap_value = get_shap_value(shap_values, analysis_label=analysis_label)\n",
    "shap.plots.beeswarm(shap_value, show=False, max_display=10)\n",
    "plt.savefig(f\"img/feature_shap_value_distribution.svg\", bbox_inches='tight')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e26402b5",
   "metadata": {},
   "source": [
    "# 具体某个样本的可解释性"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "83288d4c",
   "metadata": {},
   "outputs": [],
   "source": [
    "shap_value = get_shap_value(shap_values, analysis_label=analysis_label, samples=analysis_sample)\n",
    "shap.plots.waterfall(shap_value, max_display=10, show=False)\n",
    "plt.savefig(f\"img/{analysis_sample}_waterfall.svg\", bbox_inches='tight')\n",
    "plt.show()\n",
    "shap_value.feature_names = [f.replace('_', '\\n') + '\\n' for f in shap_value.feature_names]\n",
    "shap.plots.force(shap_value, show=False, matplotlib=True, figsize=(20, 4))\n",
    "plt.savefig(f\"img/{analysis_sample}_force.svg\", bbox_inches='tight')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0464d3aa",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
